import requests
import os
import json

# 基础URL
BASE_URL = 'http://localhost:8080/api'

# 登录获取token
def login():
    response = requests.post(f'{BASE_URL}/employee/login/', json={
        'username': 'admin',
        'password': '123456'
    })
    print("登录响应:", response.text)  # 打印响应内容
    data = response.json()
    if 'token' in data:
        return data['token']
    elif 'data' in data and 'token' in data['data']:
        return data['data']['token']
    else:
        raise Exception('登录失败：无法获取token')

# 获取第一条记录的ID
def get_first_record_id(endpoint, headers):
    response = requests.get(f'{BASE_URL}/{endpoint}/', headers=headers)
    if response.status_code == 200:
        data = response.json()
        if data.get('code') == 1 and data.get('data', {}).get('records'):
            return data['data']['records'][0]['id']
    return None

# 测试导出功能
def test_export():
    try:
        # 获取token
        token = login()
        print(f'获取到token: {token}')
        headers = {'Authorization': f'Bearer {token}'}
        
        # 创建导出目录
        export_dir = '../exports'
        if not os.path.exists(export_dir):
            os.makedirs(export_dir)
        
        # 测试Excel导出
        excel_endpoints = [
            ('stock-in/export/', 'stock_in.xlsx'),
            ('stock-out/export/', 'stock_out.xlsx'),
            ('stock-check/export/', 'stock_check.xlsx'),
            ('stock-transfer/export/', 'stock_transfer.xlsx'),
            ('stock-record/export/', 'stock_record.xlsx')
        ]
        
        print("\n测试Excel导出...")
        for endpoint, filename in excel_endpoints:
            print(f'\n正在导出 {filename}...')
            response = requests.get(f'{BASE_URL}/{endpoint}', headers=headers)
            
            print(f'响应状态码: {response.status_code}')
            print(f'响应头: {response.headers}')
            
            if response.status_code == 200:
                filepath = os.path.join(export_dir, filename)
                with open(filepath, 'wb') as f:
                    f.write(response.content)
                print(f'导出成功：{filepath}')
            else:
                print(f'导出失败：{endpoint} - 状态码 {response.status_code}')
                if response.headers.get('content-type', '').startswith('application/json'):
                    print(f'错误信息：{response.text}')
        
        # 测试PDF打印
        print("\n测试PDF打印...")
        pdf_endpoints = [
            ('stock-in', 'stock_in'),
            ('stock-out', 'stock_out'),
            ('stock-check', 'stock_check')
        ]
        
        for base_endpoint, prefix in pdf_endpoints:
            print(f'\n正在测试 {prefix} PDF打印...')
            # 获取第一条记录的ID
            record_id = get_first_record_id(base_endpoint, headers)
            if record_id:
                print(f'获取到记录ID: {record_id}')
                response = requests.get(f'{BASE_URL}/{base_endpoint}/{record_id}/print/', headers=headers)
                
                print(f'响应状态码: {response.status_code}')
                print(f'响应头: {response.headers}')
                
                if response.status_code == 200:
                    filepath = os.path.join(export_dir, f'{prefix}_{record_id}.pdf')
                    with open(filepath, 'wb') as f:
                        f.write(response.content)
                    print(f'打印成功：{filepath}')
                else:
                    print(f'打印失败：{base_endpoint} - 状态码 {response.status_code}')
                    if response.headers.get('content-type', '').startswith('application/json'):
                        print(f'错误信息：{response.text}')
            else:
                print(f'未找到 {prefix} 记录')
                
    except Exception as e:
        print(f'发生错误：{str(e)}')

if __name__ == '__main__':
    test_export() 